<template>
  <div class="echarts-generator">
    <a-button v-if="userStore.username === 'woaichitudouo'" type="primary" @click="handleAddEcharts"> 添加Echarts图表 </a-button>
  </div>
  <div class="echarts-list">
    <!-- /echarts-generator -->

    <div class="echarts-card" v-for="echarts in chartList" :key="echarts.id" @click="handleCardClick(echarts)">
      <div class="echarts-card-cover">
        <img :src="getImageUrl(echarts.previewUrl)" :alt="echarts.name" class="echarts-card-image" />
        <div class="echarts-card-tag-container">
          <div class="echarts-card-tag" v-for="tag in echarts.tags" :key="tag">{{ tag }}</div>
          <!-- 删除图标，只有特定用户才能看到 -->
          <div v-if="userStore.username === 'woaichitudouo'" class="echarts-card-delete" @click.stop="handleDeleteChart(echarts)" title="删除图表">
            <DeleteOutlined />
          </div>
        </div>
      </div>
      <div class="echarts-card-content">
        <h3 class="echarts-card-title" :title="echarts.title">{{ echarts.name }}</h3>
      </div>
    </div>
  </div>
</template>

<script setup>
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { deleteChart } from '@/utils/api'
import { Modal, message } from 'ant-design-vue'
import { DeleteOutlined } from '@ant-design/icons-vue'

const router = useRouter()
const userStore = useUserStore()

const props = defineProps({
  chartList: {
    type: Array,
    required: true
  }
})

const emit = defineEmits(['chartDeleted'])

const getImageUrl = (filename) => {
  // 构建静态资源的完整路径
  return `${import.meta.env.VITE_APP_API_BASE_URL}/assets/uploads/${filename}`
}

const handleAddEcharts = () => {
  router.push('/echarts-generator')
}

// 点击卡片跳转到详情页
const handleCardClick = (chart) => {
  // 构建路由对象
  const routeData = router.resolve({
    name: 'EchartsDetail', // 或者使用路径 path: `/echarts/${chart._id}`
    params: {
      id: chart.id
    }
  })

  // 在新窗口打开
  window.open(routeData.href, '_blank')
}

// 删除图表
const handleDeleteChart = async (chart) => {
  try {
    // 显示确认对话框
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除图表 "${chart.name}" 吗？此操作不可恢复。`,
      okText: '确认删除',
      okType: 'danger',
      cancelText: '取消',
      onOk: async () => {
        try {
          // 调用删除接口
          await deleteChart(chart.id)

          // 显示成功消息
          message.success('图表删除成功')

          // 触发父组件刷新列表
          emit('chartDeleted', chart.id)
        } catch (error) {
          console.error('删除图表失败:', error)
          message.error(error.message || '删除图表失败')
        }
      }
    })
  } catch (error) {
    console.error('删除图表操作失败:', error)
    message.error('操作失败')
  }
}
</script>

<style scoped>
@import url(./index.css);
</style>
